package com.cpr.ams.config;

import com.cpr.ams.bean.BasePrivilege;
import com.cpr.ams.exception.AmsException;
import com.cpr.ams.service.IBasePrivilegeService;
import com.cpr.ams.util.JwtTokenUtil;
import com.cpr.ams.util.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description: 权限拦截器
 * @Author: GX Cui
 * @Date 12:33 上午 2021/4/12
 */

public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private IBasePrivilegeService basePrivilegeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是options请求，直接返回true，不进行拦截
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        // 获取请求头信息authorization信息
        final String token = request.getHeader(JwtTokenUtil.AUTH_HEADER_KEY);
        if(StringUtils.isEmpty(token)){
            throw new AmsException(StatusCode.USER_NOT_LOGIN);
        }
        // 验证token是否有效--无效已做异常抛出，由全局异常处理后返回对应信息
        JwtTokenUtil.parseJWT(token, JwtTokenUtil.base64Secret);

        // 验证权限，通过token获取用户id，通过用户id获取权限，这里可以使用redis将用户信息维护在缓存中，减少与数据库交互次数
        int id = Integer.parseInt(JwtTokenUtil.getUserId(token,JwtTokenUtil.base64Secret));
        this.auth(id,request.getServletPath());

        return true;
    }

    // 判断权限
    private boolean auth(int userId,String path){
        // article/findAll
        // 查询出该用户的所有权限
        List<BasePrivilege> privileges = basePrivilegeService.findByUserId(userId);
        // 匹配
        for(BasePrivilege p : privileges){
            System.out.println(p.getRoute()+"="+path);
            if(p.getRoute().matches(path)){
                return true;
            }
        }
        throw new AmsException(StatusCode.PERMISSION_DENIED);
    }
}
